package vip.zhenzicheng.jvm.jvmbook.part2;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * 直接内存溢出demo
 * <p> VM Args: -Xmx20M -XX:MaxDirectMemorySize=10M
 *
 * @author zhenzicheng
 * @date 2022-07-19 15:54
 */
public class DirectMemoryOOM {

  private static final int _1MB = 1024 * 1024;

  public static void main(String[] args) throws IllegalAccessException {
    Field unsafeField = Unsafe.class.getDeclaredFields()[0];
    unsafeField.setAccessible(true);
    Unsafe unsafe = (Unsafe) unsafeField.get(null);
    while (true) {
      unsafe.allocateMemory(_1MB);
    }
  }
}
